package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import io.Resources;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import pojo.Configuration;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {

        //读取数据库配置
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(inputStream);
        Element rootElement = read.getRootElement();
        Element dataSourceElement = rootElement.element("dataSource");
        List<Element> elements = dataSourceElement.selectNodes("//property");

        Properties properties = new Properties();

        for (Element element : elements) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");

            properties.setProperty(name,value);
        }

        //加载数据库连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driver"));
        dataSource.setJdbcUrl(properties.getProperty("url"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(dataSource);

        //读取mapper配置文件
        List<Element> list = rootElement.selectNodes("//mapper");
        for (Element element : list) {
            String resources = element.attributeValue("resources");
            InputStream resourcesAsStream = Resources.getResourcesAsStream(resources);

            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parConfig(resourcesAsStream);
        }

        return configuration;
    }
}
